package logic

import (
	"2211a_mayi/service/mayi"
	"context"

	"2211a_mayi/api/internal/svc"
	"2211a_mayi/api/internal/types"

	"github.com/golangblogs/gojwt"
	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginRequest) (resp *types.Response, err error) {
	res, err := l.svcCtx.Service.Login(l.ctx, &mayi.LoginRequest{
		Username: req.Username,
		Password: req.Password,
	})

	if err != nil {
		return &types.Response{
			Code: 500,
			Msg:  "登录失败",
		}, nil
	}

	j := jwt.NewJWT("2211a_mayi")
	claims := jwt.CustomClaims{
		ID: uint(res.UserId),
	}

	token, _ := j.CreateToken(claims)

	return &types.Response{
		Code: 200,
		Msg:  "登录成功",
		Data: map[string]interface{}{
			"user_id": res.UserId,
			"token":   token,
		},
	}, nil
}
